import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { FeathersService } from "app/api/feathers.service";
import { Http, Headers } from '@angular/http';
import * as util from 'app/utils'
import { AccountService } from "app/api/dao/account.service";
import AccountModel from 'app/api/model/Account'
import { NedbService } from "app/service/nedb.service";
import * as Nedb from "Nedb";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  username = 'levent@qq.com'
  password = '123456'
  neonUI: any = {}

  constructor(
    private http: Http,
    private router: Router,
    private feathers: FeathersService,
    private accountDao: AccountService,
  ) { }

  ngOnInit() {
    this.setupUI()

    // this.accountDao.getAccount()
    //   .then(data => {
    //     console.log('getAccount: ' + data)
    //   })

    // this.db.insert({ planet: 'Earth' }, (err) => {
    //   this.db.find({}, (err, docs) => {
    //     console.log('db:' + docs)
    //   });
    // });

    // this.accountDao.getAccount()
    // .then(data => {
    //   console.log('getAccount: ' + data)
    // })
  }

  requestLogin() {

    // REST API
    // let headers = new Headers()
    // this.http.post(
    //   util.getConfig().server + '/authentication',
    //   {
    //     email: this.username,
    //     password: this.password,
    //   },
    //   {
    //     headers,
    //     withCredentials: false,
    //   }
    // ).subscribe({
    //   next: response => {
    //     let result: AccountModel = JSON.parse(response.text())
    //     this.accountDao.account = result
    //     console.log(result)
    //     this.resultUI(true)
    //       .then(() => this.router.navigate(['/user'], { replaceUrl: true }))
    //   },
    //   error: (error) => {
    //     console.log(error)
    //     this.resultUI(false)
    //   }
    // })

    // websocket API
    this.feathers.client.authenticate({
      email: this.username,
      password: this.password,
      strategy: 'local',
    }).then((result) => {
      this.resultUI(true)
        .then(() => this.router.navigate(['/user'], {replaceUrl: true}))
    }).catch(error => {
      this.resultUI(false)
        .then(() => this.showError())
    })
  }

  resultUI(isSuccess: boolean): Promise<any> {
    // We will give some time for the animation to finish, then execute the following procedures	
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        if (isSuccess) {
          this.neonUI.setPercentage(100)
        } else {
          $(".login-page").removeClass('logging-in');
          this.neonUI.resetProgressBar();
        }
      }, 1000)
    })
  }

  showError() {

    let $errors_container = $(".form-login-error");

    $errors_container.show();
    let height = $errors_container.outerHeight();

    $errors_container.css({
      height: 0,
    });

    TweenMax.to($errors_container, .45, {
      css: { height: height }, onComplete: function () {
        $errors_container.css({ height: 'auto' });
      }
    });

    // Reset password fields
    this.neonUI.$container.find('input[type="password"]').val('');
  }

  /**
   * demo搬过来的代码，不宜做参考
   */
  setupUI() {
    let neonLogin = this.neonUI
    let currentProgress = 0;

    neonLogin.$container = $("#form_login");
    // Login Form & Validation
    neonLogin.$container.validate({
      rules: {
        username: {
          required: true
        },

        password: {
          required: true
        },

      },

      highlight: function (element) {
        $(element).closest('.input-group').addClass('validate-has-error');
      },

      unhighlight: function (element) {
        $(element).closest('.input-group').removeClass('validate-has-error');
      },

      submitHandler: (ev) => {
        this.username = $("input#username").val()
        this.password = $("input#password").val()
        $(".login-page").addClass('logging-in'); // This will hide the login form and init the progress bar
        // Hide Errors
        $(".form-login-error").slideUp('fast');

        this.requestLogin()
        // We will wait till the transition ends				
        setTimeout(function () {
          let random_pct = 25 + Math.round(Math.random() * 30);
          // The form data are subbmitted, we can forward the progress to 70%
          neonLogin.setPercentage(40 + random_pct);

        }, 650);
      }
    });

    // Login Form Setup
    neonLogin.$body = $(".login-page");
    neonLogin.$login_progressbar_indicator = $(".login-progressbar-indicator h3");
    neonLogin.$login_progressbar = neonLogin.$body.find(".login-progressbar div");
    neonLogin.$login_progressbar_indicator.html('0%');

    if (neonLogin.$body.hasClass('login-form-fall')) {
      let focus_set = false;

      setTimeout(function () {
        neonLogin.$body.addClass('login-form-fall-init')

        setTimeout(function () {
          if (!focus_set) {
            neonLogin.$container.find('input:first').focus();
            focus_set = true;
          }

        }, 550);

      }, 0);
    }
    else {
      neonLogin.$container.find('input:first').focus();
    }

    // Focus Class
    neonLogin.$container.find('.form-control').each(function (i, el) {
      let $this = $(el),
        $group = $this.closest('.input-group');

      $this.prev('.input-group-addon').click(function () {
        $this.focus();
      });

      $this.on({
        focus: function () {
          $group.addClass('focused');
        },

        blur: function () {
          $group.removeClass('focused');
        }
      });
    });

    // Functions
    $.extend(neonLogin, {
      setPercentage: function (pct, callback) {
        pct = pct / 100 * 100 + '%';

        // Normal Login
        neonLogin.$login_progressbar_indicator.html(pct);
        neonLogin.$login_progressbar.width(pct);

        let o = {
          pct: parseInt(neonLogin.$login_progressbar.width()) / parseInt(neonLogin.$login_progressbar.parent().width()) * 100
        };

        TweenMax.to(o, .7, {
          pct: parseInt(pct, 10),
          roundProps: ["pct"],
          ease: Sine.easeOut,
          onUpdate: function () {
            neonLogin.$login_progressbar_indicator.html(o.pct + '%');
          },
          onComplete: callback
        });
      },

      resetProgressBar: function () {
        TweenMax.set(neonLogin.$container, { css: { opacity: 0 } });

        setTimeout(function () {
          TweenMax.to(neonLogin.$container, .6, {
            css: { opacity: 1 }, onComplete: function () {
              neonLogin.$container.attr('style', '');
            }
          });

          neonLogin.$login_progressbar_indicator.html('0%');
          neonLogin.$login_progressbar.width(0);

        }, 800);
      }
    });
  }
}
